import { useState } from 'react';
import dayjs from 'dayjs';
import { CheckIcon } from '@heroicons/react/24/solid';
import type { DayMark } from '../types';

// 日历组件的属性定义
interface CalendarProps {
  startDate: string;    // 开始日期
  targetDate: string;   // 目标日期
  marks: DayMark[];     // 日期标记数据
  onMarkDay: (date: string, status: 'check' | null) => void;  // 日期标记回调
}

export const Calendar = ({ startDate, targetDate, marks, onMarkDay }: CalendarProps) => {
  // 当前显示的月份，默认为当前月
  const [currentMonth, setCurrentMonth] = useState(dayjs());

  // 获取当月的所有日期，包括前置空白
  const getDaysInMonth = () => {
    // 获取当月第一天
    const firstDay = currentMonth.startOf('month');
    // 获取当月总天数
    const daysInMonth = currentMonth.daysInMonth();
    // 获取当月第一天是星期几（0-6，0 表示星期日）
    const startOffset = firstDay.day();

    const days = [];
    // 添加前置空白，用于对齐日历
    for (let i = 0; i < startOffset; i++) {
      days.push(null);
    }

    // 添加当月所有日期
    for (let i = 1; i <= daysInMonth; i++) {
      const date = currentMonth.date(i);
      days.push(date);
    }

    return days;
  };

  // 处理日期点击事件
  const handleDayClick = (date: dayjs.Dayjs) => {
    const dateStr = date.format('YYYY-MM-DD');
    // 只允许标记开始日期之后到当前日期之间的日期
    if (date.isAfter(dayjs(), 'day') || !date.isAfter(dayjs(startDate), 'day')) {
      return;
    }

    // 切换日期的标记状态
    const currentMark = marks.find(m => m.date === dateStr);
    const newStatus = currentMark?.status === 'check' ? null : 'check';

    onMarkDay(dateStr, newStatus);
  };

  return (
    <div className="w-full max-w-md mx-auto">
      {/* 日历头部：年月选择和月份切换 */}
      <div className="flex justify-between items-center mb-4">
        <button
          onClick={() => setCurrentMonth(prev => prev.subtract(1, 'month'))}
          className="p-2 hover:bg-gray-100 rounded"
        >
          &lt;
        </button>
        <div className="flex items-center gap-2">
          <select
            value={currentMonth.year()}
            onChange={(e) => setCurrentMonth(prev => prev.year(parseInt(e.target.value)))}
            className="text-xl font-semibold bg-transparent border rounded px-2"
          >
            {Array.from({ length: 10 }, (_, i) => currentMonth.year() - 5 + i).map(year => (
              <option key={year} value={year}>{year}年</option>
            ))}
          </select>
          <span className="text-xl font-semibold">{currentMonth.format('M月')}</span>
        </div>
        <button
          onClick={() => setCurrentMonth(prev => prev.add(1, 'month'))}
          className="p-2 hover:bg-gray-100 rounded"
        >
          &gt;
        </button>
      </div>

      {/* 日历主体 */}
      <div className="grid grid-cols-7 gap-1">
        {/* 星期表头 */}
        {['日', '一', '二', '三', '四', '五', '六'].map(day => (
          <div key={day} className="text-center py-2 text-gray-500">
            {day}
          </div>
        ))}

        {/* 日期格子 */}
        {getDaysInMonth().map((day, index) => {
          if (!day) return <div key={`empty-${index}`} />;

          // 计算日期状态
          const dateStr = day.format('YYYY-MM-DD');
          const mark = marks.find(m => m.date === dateStr);
          const isToday = day.isSame(dayjs(), 'day');
          const isStartDate = dateStr === startDate;
          const isTargetDate = dateStr === targetDate;
          const isClickable = !day.isAfter(dayjs(), 'day') &&
            day.isAfter(dayjs(startDate), 'day');
          const isChecked = mark?.status === 'check';

          return (
            <button
              key={dateStr}
              onClick={() => handleDayClick(day)}
              disabled={!isClickable}
              className={`
                aspect-square p-2 relative flex items-center justify-center
                ${isToday ? 'bg-blue-100' : ''}
                ${isStartDate ? 'bg-blue-500 text-white font-bold ring-4 ring-blue-200' : ''}
                ${isTargetDate ? 'bg-green-500 text-white font-bold ring-4 ring-green-200' : ''}
                ${isChecked ? 'bg-green-50 border-2 border-green-200' : ''}
                ${isClickable && !isStartDate && !isTargetDate ? 'hover:bg-gray-100' : ''}
                ${!isClickable && !isStartDate && !isTargetDate ? 'opacity-50 cursor-not-allowed' : ''}
                rounded transition-all
              `}
            >
              <span className={`${isChecked ? 'text-green-600 font-medium' : ''}`}>
                {day.date()}
              </span>
              {isChecked && (
                <CheckIcon className="w-4 h-4 text-green-500 absolute bottom-1 right-1" />
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
};